package com.fbty.mt.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.commons.lang.StringUtils;

public class IPSpeed {
	public static final String BYTES = "bytes";
	public static final String TIME = "time";
	
	public static String getSpeed(String ip){
		int num = 0;
		double total = 0.0;
		BufferedReader br = null;
		try {
			Process p = Runtime.getRuntime().exec("ping "+ip.trim());
			br = new BufferedReader(new InputStreamReader(p.getInputStream(),"gbk"));
			String line = null;
			int i=0;
			long time = System.currentTimeMillis();
			while ((line = br.readLine()) != null) {
				long temp = System.currentTimeMillis();
				if(temp>(time+4000)||i==5)
					break;
				if(i++!=1){
					String msg[] = line.split(":");
					if(msg.length==2){
						String str = StringUtils.trimToEmpty(msg[1].replaceAll("字节", IPSpeed.BYTES).replaceAll("时间", IPSpeed.TIME)).replaceAll(" ", ",");
						String[] split = str.split(",");
						if(split.length==3){
							for(String s : split){
								if(s.startsWith("time")){
									num++;
									String ms[] = s.split("=|<");
									String times = ms[1];
									total +=Double.parseDouble((times.substring(0,times.length()-2)));
								}
							}
						}
					}
				}
			}
			br.close();
			return Math.ceil(total/num)/1000+"";
		} catch (Exception e) {
			e.printStackTrace();
			return "--";
		}
	}
	

}
